package com.basic.im.pay.controller.secondpay;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.basic.im.pay.controller.secondpay.utils.SignUtil;
import com.basic.im.vo.JSONMessage;
import com.basic.utils.StringUtil;
import okhttp3.*;


import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class ThirdPay {
    // 商户密钥（请替换为实际密钥）
    public static final String MERCHANT_KEY = "e5d4ced83454d15a7ce2cf83bc7a7fe1";
    // API网关地址（请替换为实际网关地址）
    public static final String API_GATEWAY = "https://www.whpay.org/api/RechargeOrder/index.html";

    public static void main(String[] args) throws Exception {
        // 请求参数
        Map<String, Object> params = new TreeMap<>();
        params.put("merch_no", "10225");
        String orderno = StringUtil.getOutTradeNo();
        System.out.println(orderno);
        params.put("merch_order_no", orderno);
        params.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        params.put("order_amount", "100.01");
        params.put("order_currency", "USDT");
        params.put("channel_code", "801");
        params.put("notify_url", "https://www.test.com/notify.htm");
        params.put("return_url", "https://www.test.com/return.htm");
        params.put("order_language", "CN");
        params.put("merch_user_id", String.valueOf(System.currentTimeMillis() / 1000));
        params.put("request_ip", "183.253.114.189");

        // 生成签名
        String sign = SignUtil.getSign2(params, MERCHANT_KEY);
        params.put("sign", sign);

        // 发送POST请求
         String result = sendPostRequest(API_GATEWAY, params);

         Map map = new HashMap();
        JSONObject jsonObject = JSONUtil.parseObj(result);
        String code = String.valueOf( jsonObject.get("code"));
        if (!"1".equals(code)) {
             JSONMessage.failure((String) jsonObject.get("info"));
        }

        map.put("payUrl",  jsonObject.getJSONObject("data").getStr("pay_url"));
        map.put("orderNo", "1111");
         JSONMessage.success(null, map);
    }

    // 生成签名的方法
    public static String generateSign(Map<String, String> params, String key) throws Exception {
        TreeMap<String, String> sortedParams = new TreeMap<>(params);
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : sortedParams.entrySet()) {
            if (entry.getValue() != null && !entry.getValue().isEmpty()) {
                sb.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8.toString())).append("&");
            } else {
                sb.append(entry.getKey()).append("=").append("&");
            }
        }
        sb.append("key=").append(key);

        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] digest = md.digest(sb.toString().getBytes(StandardCharsets.UTF_8));
        StringBuilder hexString = new StringBuilder();
        for (byte b : digest) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }
        return hexString.toString().toLowerCase();
    }

    // 发送POST请求的方法
    public static String sendPostRequest(String urlString, Map<String, Object> params) throws Exception {
//        URL url = new URL(urlString);
//        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//        conn.setRequestMethod("POST");
//        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//        conn.setDoOutput(true);
//
//        StringBuilder sb = new StringBuilder();
//        for (Map.Entry<String, String> entry : params.entrySet()) {
//            sb.append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8.toString()))
//                    .append("=")
//                    .append(URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8.toString()))
//                    .append("&");
//        }
//        String postData = sb.toString().substring(0, sb.length() - 1);
//
//        try (OutputStream os = conn.getOutputStream()) {
//            byte[] input = postData.getBytes(StandardCharsets.UTF_8);
//            os.write(input, 0, input.length);
//        }
//
//        int responseCode = conn.getResponseCode();
//
//        System.out.println("Response Code : " + responseCode);
//        System.out.println("Response Code : " + conn.getResponseMessage());

        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Object> entry : params.entrySet()) {

            sb.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue().toString(), StandardCharsets.UTF_8.toString())).append("&");

        }
        sb.deleteCharAt(sb.length()-1);

        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, sb.toString());
        Request request = new Request.Builder()
                .url("https://www.whpay.org/api/RechargeOrder/index.html")
                .method("POST", body)
                .addHeader("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
                .addHeader("Accept", "*/*")
                .addHeader("Host", "www.whpay.org")
                .addHeader("Connection", "keep-alive")
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Cookie", "ssid=8b34a59a12507db928b50fa0cc7dab17; think_lang=zh-cn")
                .build();
        Response response = client.newCall(request).execute();
//        System.out.println(response.body().string());
        return response.body().string();
    }

}
